//
//  V2NodesViewController.m
//  V2EX
//
//  Created by 花菜ChrisCai on 2016/6/11.
//  Copyright © 2016年 Chris. All rights reserved.
//

#import "V2NodesViewController.h"
#import "V2NodeModel.h"
#import "V2NodesViewCell.h"
#import "V2DataManager.h"

@interface V2NodesViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSArray *headerTitleArray;
@property (nonatomic, strong) NSArray *nodesArray;
@property (nonatomic, strong) NSArray *myNodesArray;
@property (nonatomic, strong) NSArray *otherNodesArray;
@property (nonatomic, copy) NSString *myNodeListPath;

@property (nonatomic, copy) NSURLSessionDataTask* (^getNodeListBlock)();

@end

@implementation V2NodesViewController


#pragma mark - <初始化>


- (instancetype)initWithStyle:(UITableViewStyle)style
{
    if ([super initWithStyle:style]) {
        self.headerTitleArray = @[@"我的节点",@"分享与探索", @"V2EX", @"iOS", @"Geek", @"游戏", @"Apple", @"生活", @"Internet", @"城市", @"品牌"];
        
        self.myNodeListPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        self.myNodeListPath = [self.myNodeListPath stringByAppendingString:@"/nodes.plist"];
        
        self.myNodesArray = [NSArray arrayWithContentsOfFile:self.myNodeListPath];
        if (!self.myNodesArray) {
            self.myNodesArray = [NSArray array];
        }
        
        self.otherNodesArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NodesList" ofType:@"plist"]];
        
        [self loadData];
        
    }
    return self;
}





- (void)loadView {
    [super loadView];
    
    [self setupTableView];
    [self setupMJRefresh];
    
}

#pragma mark - <Lift Cycle>
- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = RandomColor;
    
}

#pragma mark - Setters

- (void)setNodesArray:(NSArray *)nodesArray {
    _nodesArray = nodesArray;
    
    //    [self.tableView reloadData];
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}

#pragma mark - <Data>
- (void)loadData {
    
    NSMutableArray *nodesArray = [NSMutableArray arrayWithObject:self.myNodesArray];;
    [nodesArray addObjectsFromArray:self.otherNodesArray];
    
    self.nodesArray = [self itemsWithDictArray:nodesArray];
    //tableViewController会自动reloadData
//    [self.tableView reloadData];
    
}

/**
 *  字典数组转模型数组
 */
- (NSArray *)itemsWithDictArray:(NSArray *)nodesArray {
    
    NSMutableArray *items = [NSMutableArray new];
    
    for (NSArray *sectionDictList in nodesArray) {
        NSMutableArray *setionItems = [NSMutableArray new];
        for (NSDictionary *dataDict in sectionDictList) {
            NSString *nodeTitle = dataDict[@"name"];
            NSString *nodeName = dataDict[@"title"];
            
            V2NodeModel *model = [[V2NodeModel alloc] init];
            model.nodeTitle = nodeTitle;
            model.nodeName = nodeName;
            
            [setionItems addObject:model];
        }
        [items addObject:setionItems];
    }
    
    return items;
}

#pragma mark - Configure Views & blocks

- (void)setupTableView {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.frame           = [UIScreen mainScreen].bounds;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInsetBottom = 15;
    self.tableView.contentInsetTop = 64;
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;

    
}

- (void)setupMJRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewDatas)];
    // 自动改变透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    if (self.myNodesArray.count == 0) [self.tableView.mj_header beginRefreshing];
}


- (void)loadNewDatas
{
    __weak typeof(self)weakSelf = self;
    [[V2DataManager manager] getMemberNodeListSuccess:^(NSArray *list) {
        if ([list writeToFile:weakSelf.myNodeListPath atomically:YES]) {
        }
        weakSelf.myNodesArray = list;
        [weakSelf loadData];
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
}


#pragma mark - <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.nodesArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *nodeCellIdentifier = @"nodeCellIdentifier";
    V2NodesViewCell *nodeCell = (V2NodesViewCell *)[tableView dequeueReusableCellWithIdentifier:nodeCellIdentifier];
    if (!nodeCell) {
        nodeCell = [[V2NodesViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nodeCellIdentifier];
    }
    
    nodeCell.navi = self.navigationController;
    nodeCell.nodesArray = self.nodesArray[indexPath.section];
    
    return nodeCell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [V2NodesViewCell getCellHeightWithNodesArray:self.nodesArray[indexPath.section]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 36;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0, 0, V2ScreenWidth, 36}];
    headerView.backgroundColor = [UIColor darkGrayColor];
    
    UILabel *label                       = [[UILabel alloc] initWithFrame:(CGRect){10, 0, V2ScreenWidth - 20, 36}];
    label.textColor                      = [UIColor blackColor];
    label.font                           = [UIFont systemFontOfSize:15.0];
    label.text                           = self.headerTitleArray[section];
    [headerView addSubview:label];
    
    if (section == 0) {
        UIView *topBorderLineView            = [[UIView alloc] initWithFrame:(CGRect){0, 0, V2ScreenWidth, 0.5}];
        topBorderLineView.backgroundColor    = [UIColor darkGrayColor];
        [headerView addSubview:topBorderLineView];
    }
    
    UIView *bottomBorderLineView         = [[UIView alloc] initWithFrame:(CGRect){0, 35.5, V2ScreenWidth, 0.5}];
    bottomBorderLineView.backgroundColor = [UIColor darkGrayColor];
    [headerView addSubview:bottomBorderLineView];
    
    
    return headerView;
}


@end
